package event

import (
	"alex/ptp1588boundaryclock/datatypes"
)

type Pdelay_ReqMessage struct {
	Timestamp *datatypes.TimeStamp
}

func (a* Pdelay_ReqMessage) Init() {
	a.Timestamp = new(datatypes.TimeStamp)
}

// =====================================================================================================================
// Write Pdelay_Req Message
// =====================================================================================================================

// Writes the Pdelay_Req Message
func (a *Pdelay_ReqMessage) Write(pdelay_req []byte, done chan bool) {
	// 13.9.2.1 originTimestamp (Timestamp)
	// 11.4.3 a)3) Shall set the originTimestamp to 0 or an estimate no worse than ±1 s of the egress timestamp, t1, of the Pdelay_Req message.
	for i := 0; i < 10; i++ {
		pdelay_req[i] = 0
	}
	// 13.9.1 The reserved field in the Pdelay_Req message is to make the message length match the length of the Pdelay_Resp message.
	for i := 10; i < 20; i++ {
		pdelay_req[i] = 0
	}
	done <- true
}

// =====================================================================================================================
// Read Pdelay_Req Message
// =====================================================================================================================

// Reads, checks and sets the Pdelay_Req Message values
func (a* Pdelay_ReqMessage) Read(pdelay_req []byte) (check bool) {
	check = true
	// 13.9.2.1 originTimestamp (Timestamp)
	a.readTimestamp(pdelay_req[:10])
	// 13.9.1 The reserved field in the Pdelay_Req message is to make the message length match the length of the Pdelay_Resp message.
	if pdelay_req[12] != 0 {
		check = false
	}
	return
}

// Reads and sets the 13.9.2.1 originTimestamp (Timestamp)
func (a* Pdelay_ReqMessage) readTimestamp(timestamp []byte) {
	// we use uint64 since uint48 is not available in Go
	a.Timestamp.SecondsField = uint64(timestamp[0]) << 40 | uint64(timestamp[1]) << 32 | uint64(timestamp[2]) <<
			24 | uint64(timestamp[3]) << 16 | uint64(timestamp[4]) << 8 | uint64(timestamp[5])
	a.Timestamp.NanosecondsField = uint32(timestamp[6]) << 24 | uint32(timestamp[7]) << 16 | uint32(timestamp[8]) <<
			8 | uint32(timestamp[9])
}
